<template>
    <div>
        <NavBar>
            <template #default>
                首页
            </template>
        </NavBar>
        <SearchBar />
        <BannerView :bannerData="banners" />
        <RecommendView :recommendData="recommends" />
        <TabControl :tabData="tabs" @tabClick="tabClick" />
        <GoodsList :goodsData="goods[currentType]?.records || []" />
        <div v-if="loading" class="loading-text">加载中...</div>
        <div v-if="noMore" class="no-more-text">没有更多了</div>
    </div>
</template>

<script setup>
import { onMounted, reactive, ref, onUnmounted } from 'vue';
import NavBar from '../../components/common/NavBar.vue';
import SearchBar from '../../components/common/SearchBar.vue';
import BannerView from './BannerView.vue';
import RecommendView from './RecommendView.vue';
import TabControl from '../../components/content/TabControl.vue';
import GoodsList from '../../components/content/GoodsList.vue';
import { ElMessage } from 'element-plus' // 引入element-plus的消息提示组件

import { getAllBannerList } from '@/api/BannerApi'
import { getAllCategoryList } from '@/api/CategoryApi.js'
import { getDiscountList } from '@/api/ProductApi'

const banners = ref([]);
const recommends = ref([]);
const tabs = ref([]);

const currentType = ref('deal');
const goods = reactive({});
const loading = ref(false);
const noMore = ref(false);
const pagination = reactive({
    deal: { current: 1, size: 1, total: 0, pages: 0 },
    hot: { current: 1, size: 1, total: 0, pages: 0 },
    guess: { current: 1, size: 1, total: 0, pages: 0 }
});

const tabClick = async (index) => {
    currentType.value = tabs.value[index].name;
    console.log('当前tab:', currentType.value);

    // 重置分页状态
    noMore.value = false;

    // 动态加载对应 tab 的商品
    if (!goods[currentType.value]) {
        await loadGoods(currentType.value, true);
    }
};

const loadGoods = async (type, reset = false) => {
    if (loading.value || noMore.value) return;

    loading.value = true;

    try {
        const pageInfo = pagination[type];
        if (reset) {
            pageInfo.current = 1;
        }

        let res;
        if (type === 'deal') {
            res = await getDiscountList(pageInfo.current, pageInfo.size);
        } else if (type === 'hot') {
            // res = await getHotList(pageInfo.current, pageInfo.size);
        } else if (type === 'guess') {
            // res = await getGuessList(pageInfo.current, pageInfo.size);
        }

        if (res.code === 1) {
            const newRecords = res.data.records || [];

            if (reset) {
                goods[type] = res.data;
            } else {
                goods[type].records = [...(goods[type].records || []), ...newRecords];
                goods[type].total = res.data.total;
                goods[type].pages = res.data.pages;
            }

            // 更新分页信息
            pagination[type] = {
                current: res.data.current,
                size: res.data.size,
                total: res.data.total,
                pages: res.data.pages
            };

            // 检查是否还有更多数据
            if (res.data.current >= res.data.pages) {
                noMore.value = true;
            } else {
                pagination[type].current += 1;
            }
        } else {
            ElMessage.error(`加载${type}商品失败`);
        }
    } catch (error) {
        console.error('加载商品出错:', error);
        ElMessage.error(`加载${type}商品失败`);
    } finally {
        loading.value = false;
    }
};

const handleScroll = () => {
    const scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
    const windowHeight = document.documentElement.clientHeight || document.body.clientHeight;
    const scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;

    // 距离底部100px时加载更多
    if (scrollTop + windowHeight >= scrollHeight - 100 && !loading.value && !noMore.value) {
        loadGoods(currentType.value);
    }
};

onMounted(async () => {
    try {
        const response = await getAllBannerList()
        console.log('完整响应:', response)

        if (response.code === 1) {
            banners.value = response.data;
        }
    } catch (error) {
        console.error('获取轮播图失败:', error)
        ElMessage.error('加载轮播图失败')
    }
});

onMounted(async () => {
     try {
        const response = await getAllCategoryList()
        console.log('完整响应:', response)

        if (response.code === 1) {
            recommends.value = response.data
        }
    } catch (error) {
        console.error('获取分类列表失败:', error)
        ElMessage.error('加载分类列表失败')
    }
});

onMounted(async () => {
    const res = await fetch('/tabs.json');
    const data = await res.json();
    tabs.value = data.data;

    // 默认选中第一个 tab，并加载商品
    currentType.value = tabs.value[0].name;
    await loadGoods(currentType.value, true);

    // 添加滚动事件监听
    window.addEventListener('scroll', handleScroll);
});

onUnmounted(() => {
    // 移除滚动事件监听
    window.removeEventListener('scroll', handleScroll);
});

</script>

<style scoped>
.loading-text, .no-more-text {
    text-align: center;
    padding: 10px;
    color: #999;
}
</style>